/* Hawk - A Component Based Test Framework
 *
 * Copyright (C) 2010 http://code.google.com/p/hawk-framework/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
package org.hawk.applications.finder.swing.communication;

import java.io.IOException;

import javax.bluetooth.RemoteDevice;

import net.java.dev.marge.communication.ConnectionListener;
import net.java.dev.marge.entity.ServerDevice;
import net.java.dev.marge.entity.config.ServerConfiguration;
import net.java.dev.marge.factory.CommunicationFactory;
import net.java.dev.marge.factory.RFCOMMCommunicationFactory;

import org.hawk.applications.finder.swing.gui.TabProfile;

/**
 * 
 * @author Rodrigo Prestes Machado
 */
public class ThreadServer extends Thread {

	public void run() {
		
		System.out.println("Starting device server ...");
		
		// Creating a factory using RFCOMM protocol if you want to use L2CAP protocol 
		//instead, try L2CAPCommunicationFactory
		CommunicationFactory factory = new RFCOMMCommunicationFactory();

		// Creating a server configuration. You can set specific configurations using 
		//this class.
		ServerConfiguration sconf = new ServerConfiguration(new CommunicationListenerImpl());

		// Creating a server with the factory. The server device instance will be
		//returned by the ConnectionListenerImpl, 
		//which is a implementation of ConnectionListener.
		factory.waitClients(sconf, new ConnectionListenerImpl());
	
	}

	/**
	 * 
	 * @author Rodrigo Prestes Machado
	 */
	private class ConnectionListenerImpl implements ConnectionListener {

		@Override
		public void connectionEstablished(ServerDevice serverDevice, RemoteDevice device) {
			
			// Debug
			System.out.println("Connection Established");
			System.out.println("Device: " + device.toString());
			
			// Sends a message to connected client
			serverDevice.send(TabProfile.getProfile());
			
			// Listen the clients messages
			serverDevice.startListening();
		}

		@Override
		public void errorOnConnection(IOException error) {
			System.out.println("Error On Connection");

		}

		@Override
		public void initialisationSucessful() {
			System.out.println("Initialisation Sucessful");
		}

	}

	
	
}